from odoo import fields, models, api, _
from odoo.tools.float_utils import float_compare, float_is_zero
from odoo.exceptions import ValidationError, UserError


class QualityAlert(models.Model):
    _inherit = 'quality.alert'
    _order = 'id desc'

    subcon_ids = fields.One2many('quality.subcon.line', 'quality_alert_id')
    # 外包数量
    subcon_qty = fields.Float(compute='compute_get_subcon_qty', store=True)

    # 统计外发接收数量 接收数 = 总接收数 - 报废数
    @api.depends('subcon_ids', 's_scrap_ids')
    def compute_get_subcon_qty(self):
        self = self.sudo()
        for record in self:
            # 外发数量
            product_qty = round(sum(record.subcon_ids.mapped('product_qty')), 4)
            record.subcon_qty = product_qty
            # 收入数量
            qty_received = round(sum(record.subcon_ids.mapped('qty_received')), 4)
            # 报废数量
            scrap_qty = round(sum(record.s_scrap_ids.mapped('scrap_qty')), 4)
            record.poor_subcon_qty = round(scrap_qty, 4)
            # 实际 = 收入 - 报废
            record.good_subcon_qty = round(qty_received - scrap_qty, 4)


class QualitySubconLine(models.Model):
    _name = 'quality.subcon.line'
    _description = 'Quality Subcon Line'

    quality_alert_id = fields.Many2one('quality.alert')
    subcon_line_id = fields.Many2one('stock.subcon.outside.line')
    purchase_id = fields.Many2one('purchase.order', 'Purchase Order', related='subcon_line_id.purchase_id', store=True)
    product_id = fields.Many2one('product.product', 'Product', related='subcon_line_id.product_id', store=True)
    name = fields.Text('Name', related='subcon_line_id.name', store=True)
    product_qty = fields.Float('Product Qty')  # 订购数
    qty_received = fields.Float('Received Qty')  # 实际接收数
    product_uom = fields.Many2one('uom.uom', 'Product UOM', related='subcon_line_id.product_uom', store=True)
    s_specs = fields.Char('Specs', related='subcon_line_id.s_specs', store=True)
